Solving String Reversal, Palindrome, and Character Frequency Problems in Java
Course: Core Java Training
Topic: Solving String Reversal, Palindrome, and Character Frequency Problems
Course Link: Core Java Training Course
Demo Link: Register for a Course Demo
Website: JustAcademy
1. Introduction
String manipulation is an important part of Core Java programming. Many programming exercises and interview questions require developers to process text, examine individual characters, compare character sequences, and count repeated values.
Three common string problems are string reversal, palindrome checking, and character frequency counting. These problems help beginners understand loops, conditional statements, arrays, String methods, character operations, and algorithmic complexity.
- String reversal: Arranging the characters of a string in reverse order.
- Palindrome checking: Determining whether a string reads the same forward and backward according to a defined comparison rule.
- Character frequency: Counting how many times each character appears in a string.
Java provides the String class for working with text and the StringBuilder class for efficiently constructing and modifying character sequences. String objects are immutable, so operations that produce modified text return a new result rather than changing the original string. Read the Java String API documentation.
2. Learning Objectives
After completing this topic, you should be able to:
- Understand common string-processing problems.
- Reverse a string using loops, character arrays, and StringBuilder.
- Check whether a word or sentence is a palindrome.
- Perform case-insensitive palindrome checks.
- Ignore spaces and punctuation when checking a sentence for a palindrome.
- Count the frequency of each character.
- Find the most frequent and least frequent characters.
- Count vowels, consonants, digits, spaces, and special characters.
- Choose appropriate data structures for frequency counting.
- Analyze time and space complexity.
- Handle empty strings, null references, and Unicode considerations.
3. Understanding String Reversal
String reversal means arranging the characters in the opposite order from the original string. The first character becomes the last, the second becomes the second-last, and so on.
For example:
| Original String |
Reversed String |
Java |
avaJ |
Hello |
olleH |
12345 |
54321 |
Level |
leveL |
ABC |
CBA |
String reversal is useful for learning index manipulation, working with character arrays, solving palindrome problems, and understanding algorithms.
4. Reversing a String Using a for Loop
One beginner-friendly approach is to traverse the original string from its last index to its first index. Each character is appended to a new result.
Algorithm
- Declare the original string.
- Create an empty result string.
- Start a loop at
text.length() - 1.
- Move backward until index zero is reached.
- Append each character to the result.
- Print the reversed string.
Example Program
public class ReverseStringLoop {
public static void main(String[] args) {
String text = "Java";
String reversed = "";
for (int i = text.length() - 1; i >= 0; i--) {
reversed += text.charAt(i);
}
System.out.println("Original: " + text);
System.out.println("Reversed: " + reversed);
}
}
Output:
Original: Java
Reversed: avaJ
Explanation
text.length() - 1 calculates the final valid index.
charAt(i) accesses the character at the current index.
- The loop moves backward by decrementing
i.
- The
+= operation combines each character with the result.
Performance note: This version is easy to understand, but repeatedly concatenating strings can create many intermediate objects. For longer strings, a StringBuilder or character-array approach is preferable.
5. Reversing a String Using StringBuilder
The StringBuilder class provides a built-in reverse() method. It is a convenient approach for reversing strings without repeatedly creating intermediate strings during the reversal.
Example Program
public class ReverseStringBuilder {
public static void main(String[] args) {
String text = "Programming";
String reversed = new StringBuilder(text)
.reverse()
.toString();
System.out.println("Original: " + text);
System.out.println("Reversed: " + reversed);
}
}
Output:
Original: Programming
Reversed: gnimmargorP
How It Works
new StringBuilder(text) initializes a mutable character sequence.
reverse() reverses that sequence.
toString() returns the result as a String object.
This is generally the simplest approach for ordinary Java string-reversal exercises. Java's String class itself does not provide a reverse() method.
6. Reversing a String Using a Character Array
A character array allows direct access to individual positions. The two-pointer technique swaps characters from opposite ends and moves toward the middle.
Algorithm
- Convert the string into a character array using
toCharArray().
- Initialize one pointer at the beginning and another at the end.
- Swap the characters at both positions.
- Move the left pointer forward and the right pointer backward.
- Continue until the pointers meet or cross.
- Create a string from the resulting array.
Example Program
public class ReverseUsingArray {
public static void main(String[] args) {
String text = "Hello";
char[] characters = text.toCharArray();
int left = 0;
int right = characters.length - 1;
while (left < right) {
char temp = characters[left];
characters[left] = characters[right];
characters[right] = temp;
left++;
right--;
}
String reversed = new String(characters);
System.out.println(reversed);
}
}
Output:
olleH
This approach demonstrates array manipulation and is useful when learning algorithms that use two pointers.
7. Reversing a String Using Recursion
Recursion occurs when a method calls itself to solve a smaller version of the same problem. A recursive string-reversal method can take the first character and append it after reversing the remaining substring.
Example Program
public class RecursiveStringReverse {
static String reverse(String text) {
if (text.isEmpty()) {
return text;
}
return reverse(text.substring(1)) + text.charAt(0);
}
public static void main(String[] args) {
String text = "Java";
System.out.println(reverse(text));
}
}
Output:
avaJ
Explanation
- The base case returns when the string is empty.
- The recursive call processes the substring after the first character.
- The original first character is appended to the end of the recursive result.
Although this method demonstrates recursion clearly, repeated substring creation and recursive calls can use more memory and processing time than an iterative approach. For large inputs, prefer an iterative algorithm or StringBuilder.
8. Comparing String Reversal Approaches
| Approach |
Main Technique |
Advantages |
Limitations |
| Loop with concatenation |
Traverse backward and append |
Easy for beginners |
Repeated concatenation can be inefficient |
| StringBuilder |
Use reverse() |
Simple and convenient |
Uses a mutable helper object |
| Character array |
Swap characters with two pointers |
Teaches array algorithms |
Needs explicit swapping logic |
| Recursion |
Reverse smaller substrings |
Demonstrates recursive thinking |
Can use substantial call-stack space |
9. Understanding Palindrome Problems
A palindrome is a sequence that reads the same forward and backward under a defined comparison rule. Common examples include words, numbers represented as strings, and sentences after removing spaces and punctuation.
| Value |
Palindrome? |
Reason |
madam |
Yes |
Same forward and backward |
level |
Yes |
Same character sequence in both directions |
radar |
Yes |
Reversing it produces the same text |
java |
No |
Reverse is avaj |
121 |
Yes |
Same when reversed |
1234 |
No |
Reverse is 4321 |
Before implementing a palindrome check, decide whether the comparison should be case-sensitive and whether spaces, punctuation, and non-letter characters should be considered.
10. Checking a Palindrome by Reversing the String
The simplest palindrome algorithm reverses the string and compares the reversed result with the original.
Algorithm
- Store the input string.
- Reverse it using StringBuilder.
- Compare the original and reversed strings using
equals().
- Print whether the string is a palindrome.
Example Program
public class PalindromeUsingReverse {
public static void main(String[] args) {
String text = "madam";
String reversed = new StringBuilder(text)
.reverse()
.toString();
if (text.equals(reversed)) {
System.out.println("Palindrome");
} else {
System.out.println("Not a palindrome");
}
}
}
Output:
Palindrome
Testing Another Word
String text = "hello";
String reversed = new StringBuilder(text).reverse().toString();
System.out.println(text.equals(reversed));
Output:
false
This method is simple and readable, but it creates a reversed copy of the input string. A two-pointer approach can check a palindrome without building a separate reversed string.
11. Checking a Palindrome Using Two Pointers
The two-pointer technique compares characters from opposite ends of the string. If every corresponding pair matches, the string is a palindrome. If any pair differs, the string is not a palindrome.
Algorithm
- Set
left to zero.
- Set
right to text.length() - 1.
- Compare the characters at the two positions.
- If they differ, return false.
- Move the left pointer forward and the right pointer backward.
- Return true if the pointers meet or cross without a mismatch.
Example Program
public class PalindromeTwoPointers {
static boolean isPalindrome(String text) {
int left = 0;
int right = text.length() - 1;
while (left < right) {
if (text.charAt(left) != text.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
public static void main(String[] args) {
System.out.println(isPalindrome("level"));
System.out.println(isPalindrome("java"));
System.out.println(isPalindrome("madam"));
}
}
Output:
true
false
true
The algorithm stops early when it finds a mismatch. It does not need to reverse or copy the entire string.
12. Checking a Palindrome Without Case Sensitivity
Sometimes uppercase and lowercase letters should be treated as equivalent. For example, "Madam" may be considered a palindrome when letter case is ignored.
One approach is to convert the text to a consistent case before checking it.
Example Program
public class CaseInsensitivePalindrome {
public static void main(String[] args) {
String text = "Madam";
String normalized = text.toLowerCase();
String reversed = new StringBuilder(normalized)
.reverse()
.toString();
if (normalized.equals(reversed)) {
System.out.println("Palindrome ignoring case");
} else {
System.out.println("Not a palindrome");
}
}
}
Output:
Palindrome ignoring case
For language-sensitive text, case conversion may depend on locale. The example demonstrates a common beginner approach for ordinary English text, not a complete Unicode normalization solution.
13. Checking Sentence Palindromes While Ignoring Spaces and Punctuation
Sentence palindrome problems often require ignoring whitespace, punctuation, and letter case. For example, the sentence "A man, a plan, a canal: Panama" is commonly treated as a palindrome after removing non-alphanumeric characters and converting letters to a consistent case.
Algorithm
- Create a StringBuilder for the normalized text.
- Process each character in the original string.
- Keep only letters and digits.
- Convert each retained character to lowercase.
- Compare the normalized string with its reverse.
Example Program
public class SentencePalindrome {
static boolean isPalindrome(String text) {
StringBuilder normalized = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
if (Character.isLetterOrDigit(ch)) {
normalized.append(Character.toLowerCase(ch));
}
}
String cleaned = normalized.toString();
String reversed = normalized.reverse().toString();
return cleaned.equals(reversed);
}
public static void main(String[] args) {
String sentence = "A man, a plan, a canal: Panama";
System.out.println(isPalindrome(sentence));
}
}
Output:
true
This example handles many ordinary English inputs. Since it processes Java char values, supplementary Unicode characters represented by surrogate pairs require additional care. Unicode normalization may also be necessary when visually identical text can have different underlying character sequences.
14. Understanding Character Frequency
Character frequency is the number of times a particular character appears in a string. A frequency-counting program may count one selected character or count every character in the input.
For example, consider the string "banana".
| Character |
Frequency |
b |
1 |
a |
3 |
n |
2 |
Character frequency is useful for text analysis, finding duplicate characters, counting letters, solving anagram problems, and understanding basic data structures.
15. Counting the Frequency of One Character
To count one particular character, traverse the string and increment a counter whenever the current character matches the target character.
Algorithm
- Declare the input string and target character.
- Initialize a counter to zero.
- Traverse each character in the string.
- Compare each character with the target.
- Increment the counter when they match.
- Print the final count.
Example Program
public class SingleCharacterFrequency {
public static void main(String[] args) {
String text = "programming";
char target = 'g';
int count = 0;
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == target) {
count++;
}
}
System.out.println("Character: " + target);
System.out.println("Frequency: " + count);
}
}
Output:
Character: g
Frequency: 2
16. Counting All Character Frequencies Using an Array
For strings containing basic English ASCII characters, an integer array of length 128 can count the frequency of each ASCII character. The character's numeric value is used as an array index.
This approach is suitable for a restricted ASCII input. It should not be used as a general Unicode frequency counter because many valid characters have code points outside the ASCII range.
Example Program
public class AsciiCharacterFrequency {
public static void main(String[] args) {
String text = "banana";
int[] frequency = new int[128];
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
if (ch < 128) {
frequency[ch]++;
}
}
for (int i = 0; i < frequency.length; i++) {
if (frequency[i] > 0) {
System.out.println((char) i + " : " + frequency[i]);
}
}
}
}
Output:
a : 3
b : 1
n : 2
Explanation
int[] frequency = new int[128] creates counters for ASCII values.
frequency[ch]++ increments the counter associated with the character.
- The second loop prints only characters with a frequency greater than zero.
- Because ASCII values are visited in increasing order, the output follows ASCII character order.
17. Counting Frequencies Using HashMap
A HashMap stores key-value pairs. For character frequency, the key represents a character and the value represents its count. This approach is flexible and can support a wider range of Java characters than a small fixed ASCII array.
Example Program
import java.util.HashMap;
import java.util.Map;
public class CharacterFrequencyMap {
public static void main(String[] args) {
String text = "programming";
Map<Character, Integer> frequency = new HashMap<>();
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
frequency.put(
ch,
frequency.getOrDefault(ch, 0) + 1
);
}
for (Map.Entry<Character, Integer> entry
: frequency.entrySet()) {
System.out.println(
entry.getKey() + " : " + entry.getValue()
);
}
}
}
Possible Output:
p : 1
r : 2
o : 1
g : 2
a : 1
m : 2
i : 1
n : 1
The iteration order of a HashMap is not guaranteed. The order shown above is illustrative; your output may display the same counts in a different order.
Understanding getOrDefault()
The expression frequency.getOrDefault(ch, 0) retrieves the current count for the character. If the character has not appeared before, it returns zero. Adding one and storing the result updates the count.
18. Printing Character Frequencies in Insertion Order
If the output should follow the order in which characters first appear, use LinkedHashMap instead of HashMap.
Example Program
import java.util.LinkedHashMap;
import java.util.Map;
public class OrderedCharacterFrequency {
public static void main(String[] args) {
String text = "banana";
Map<Character, Integer> frequency =
new LinkedHashMap<>();
for (char ch : text.toCharArray()) {
frequency.put(
ch,
frequency.getOrDefault(ch, 0) + 1
);
}
for (Map.Entry<Character, Integer> entry
: frequency.entrySet()) {
System.out.println(
entry.getKey() + " : " + entry.getValue()
);
}
}
}
Output:
b : 1
a : 3
n : 2
LinkedHashMap maintains insertion order by default, so each character is printed in the order it first appears in the input.
19. Counting Vowels and Consonants
A common string-processing exercise is to count the vowels and consonants in a word or sentence. For basic English text, vowels are usually treated as a, e, i, o, and u.
Example Program
public class VowelConsonantCount {
public static void main(String[] args) {
String text = "Core Java";
int vowels = 0;
int consonants = 0;
for (int i = 0; i < text.length(); i++) {
char ch = Character.toLowerCase(text.charAt(i));
if (ch >= 'a' && ch <= 'z') {
if ("aeiou".indexOf(ch) >= 0) {
vowels++;
} else {
consonants++;
}
}
}
System.out.println("Vowels: " + vowels);
System.out.println("Consonants: " + consonants);
}
}
Output:
Vowels: 4
Consonants: 4
The program ignores spaces and characters outside the basic English alphabet. Its definition of vowels and consonants is intended for introductory English-language exercises; other languages may require different rules.
20. Counting Letters, Digits, Spaces, and Special Characters
Java provides methods in the Character class to classify characters. These methods are more useful than checking only a narrow set of ASCII values when processing ordinary Unicode letters and digits.
Example Program
public class CharacterTypeCounter {
public static void main(String[] args) {
String text = "Java 17 @ Core!";
int letters = 0;
int digits = 0;
int spaces = 0;
int special = 0;
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
if (Character.isLetter(ch)) {
letters++;
} else if (Character.isDigit(ch)) {
digits++;
} else if (Character.isWhitespace(ch)) {
spaces++;
} else {
special++;
}
}
System.out.println("Letters: " + letters);
System.out.println("Digits: " + digits);
System.out.println("Spaces: " + spaces);
System.out.println("Special characters: " + special);
}
}
Output:
Letters: 8
Digits: 2
Spaces: 3
Special characters: 2
This example classifies individual Java char values. Some supplementary Unicode characters occupy two UTF-16 code units, so counting full Unicode code points requires a different approach.
21. Finding the Most Frequent Character
Once the character frequency map has been created, the program can find the character with the highest count by examining each entry.
Example Program
import java.util.HashMap;
import java.util.Map;
public class MostFrequentCharacter {
public static void main(String[] args) {
String text = "success";
Map<Character, Integer> frequency = new HashMap<>();
for (char ch : text.toCharArray()) {
frequency.put(
ch,
frequency.getOrDefault(ch, 0) + 1
);
}
char mostFrequent = '\0';
int maximum = 0;
for (Map.Entry<Character, Integer> entry
: frequency.entrySet()) {
if (entry.getValue() > maximum) {
maximum = entry.getValue();
mostFrequent = entry.getKey();
}
}
System.out.println("Most frequent character: "
+ mostFrequent);
System.out.println("Frequency: " + maximum);
}
}
Output:
Most frequent character: s
Frequency: 3
If multiple characters have the same maximum frequency, this implementation selects whichever tied character is encountered first during HashMap iteration. To make tie-breaking deterministic, use an ordered map or define a specific tie-breaking rule.
22. Finding Duplicate Characters
A duplicate character is a character that occurs more than once in the input string. A frequency map makes it straightforward to identify such characters.
Example Program
import java.util.LinkedHashMap;
import java.util.Map;
public class DuplicateCharacters {
public static void main(String[] args) {
String text = "programming";
Map<Character, Integer> frequency =
new LinkedHashMap<>();
for (char ch : text.toCharArray()) {
frequency.put(
ch,
frequency.getOrDefault(ch, 0) + 1
);
}
System.out.println("Duplicate characters:");
for (Map.Entry<Character, Integer> entry
: frequency.entrySet()) {
if (entry.getValue() > 1) {
System.out.println(
entry.getKey() + " : " + entry.getValue()
);
}
}
}
}
Output:
Duplicate characters:
r : 2
g : 2
m : 2
The LinkedHashMap keeps the output in the order of each character's first appearance. Only characters with a frequency greater than one are printed.
23. Checking Whether Two Strings Are Anagrams
An anagram is a word or phrase formed by rearranging the letters of another word or phrase, usually with the same character counts. For example, "listen" and "silent" are anagrams when case and formatting are treated consistently.
Character frequency is one way to solve this problem. If the normalized strings have the same character counts, they are anagrams under the chosen normalization rules.
Example Program for Basic English Letters
import java.util.Arrays;
public class AnagramChecker {
static boolean areAnagrams(String first, String second) {
if (first == null || second == null) {
return false;
}
String a = first.replaceAll("\\s+", "")
.toLowerCase();
String b = second.replaceAll("\\s+", "")
.toLowerCase();
if (a.length() != b.length()) {
return false;
}
char[] firstChars = a.toCharArray();
char[] secondChars = b.toCharArray();
Arrays.sort(firstChars);
Arrays.sort(secondChars);
return Arrays.equals(firstChars, secondChars);
}
public static void main(String[] args) {
System.out.println(areAnagrams("listen", "silent"));
System.out.println(areAnagrams("hello", "world"));
}
}
Output:
true
false
This example removes whitespace and ignores letter case, but it retains punctuation. For multilingual text, a complete anagram definition may need Unicode normalization and code-point-aware processing.
24. Handling Empty Strings and Null Values
Robust string algorithms should account for empty input and null references.
- Empty string: A valid String object containing zero characters.
- Null reference: A reference that does not point to a String object.
- Whitespace-only string: A string containing spaces or other whitespace characters.
Example
public class SafeStringProcessing {
public static void main(String[] args) {
String text = "";
if (text == null) {
System.out.println("Input is null.");
} else if (text.isEmpty()) {
System.out.println("Input is empty.");
} else {
System.out.println(
new StringBuilder(text).reverse()
);
}
}
}
Output:
Input is empty.
An empty string is generally a palindrome under the standard algorithm because there are no mismatched character pairs. Whether empty input should be accepted as valid depends on the application's requirements.
25. Unicode Considerations in String Problems
Java strings use UTF-16 internally. A Java char represents one 16-bit code unit, not always a complete Unicode character. Characters outside the Basic Multilingual Plane, including many emoji, are represented by a pair of code units.
For many basic English programming exercises, loops using charAt() are sufficient. When a task requires processing full Unicode code points, consider methods such as codePoints(), Character.isLetter(int), and Character.isDigit(int).
Example: Counting Unicode Code Points
public class UnicodeCodePointCount {
public static void main(String[] args) {
String text = "A😊B";
System.out.println("UTF-16 units: " + text.length());
System.out.println("Code points: "
+ text.codePointCount(0, text.length()));
}
}
Output:
UTF-16 units: 4
Code points: 3
This distinction matters for reversing strings, counting characters, and palindrome checks involving supplementary Unicode characters. Even code points are not always the same as user-perceived grapheme clusters; some displayed symbols consist of multiple code points.
26. Time and Space Complexity
Time complexity describes how the processing time grows as input size increases. Space complexity describes how the extra memory requirement grows with the input size.
| Problem or Approach |
Typical Time Complexity |
Extra Space |
| Reverse using StringBuilder |
O(n) |
O(n) for the resulting mutable sequence and output |
| Reverse using a character array |
O(n) |
O(n) for the array copy |
| Palindrome using two pointers |
O(n) worst case |
O(1) auxiliary space |
| Palindrome using reversed copy |
O(n) |
O(n) |
| Count one character |
O(n) |
O(1) |
| Count ASCII characters using a fixed array |
O(n + k) |
O(k), where k is the fixed alphabet size |
| Count distinct characters using a map |
O(n) expected |
O(k), where k is the number of distinct keys |
| Sort characters for anagram comparison |
O(n log n) |
O(n) |
Here, n is the input length and k is the number of possible or distinct characters being counted. These are typical complexity estimates; exact behavior depends on the implementation and the input.
27. Common Mistakes and Troubleshooting
| Mistake |
Why It Happens |
How to Fix It |
Starting a reverse loop at length() |
String indexes begin at zero |
Start at length() - 1 |
Using i > 0 in a reverse loop |
The loop skips index zero |
Use i >= 0 |
Comparing strings with == |
Checks reference identity rather than content equality |
Use equals() |
| Forgetting to increment a frequency counter |
The counter remains unchanged |
Use count++ when a match occurs |
| Using a 128-element array for all Unicode text |
Many character values exceed the ASCII range |
Use an appropriate map or code-point-based approach |
| Counting spaces as letters |
No character classification is applied |
Use Character.isLetter() or a defined normalization rule |
| Ignoring uppercase and lowercase differences |
The comparison rule was not specified |
Normalize case or use an appropriate case-insensitive comparison |
| Ignoring punctuation in a palindrome test without a requirement |
The algorithm silently changes the input rules |
Define whether punctuation and spaces count |
| Assuming HashMap output order |
HashMap does not guarantee iteration order |
Use LinkedHashMap or sort entries when order matters |
| Passing null to a string-processing method |
The reference does not point to an object |
Validate null before processing |
28. Best Practices for Solving String Problems
- Understand the problem requirements before writing code.
- Decide whether comparison should be case-sensitive.
- Determine whether spaces, punctuation, and digits should be included.
- Use StringBuilder for convenient string reversal and repeated text construction.
- Use the two-pointer technique when checking palindromes without creating a reversed copy.
- Use a fixed-size array only when the input character set is known and bounded.
- Use HashMap or LinkedHashMap when flexible character counting is required.
- Use
Character utility methods to classify letters, digits, and whitespace.
- Check null values and empty strings before processing.
- Test algorithms with normal, empty, single-character, repeated-character, and mixed-case inputs.
- Consider Unicode code points when the program must support a broad range of languages and symbols.
- Explain the time and space complexity when presenting a solution in an interview.
29. Practice Exercises
Exercise 1: Reverse a String
- Create a string containing your name.
- Reverse it using a for loop.
- Reverse it again using StringBuilder.
- Compare both results.
Exercise 2: Check a Palindrome
- Write a method named
isPalindrome().
- Test it with
"madam", "level", and "java".
- Return a boolean instead of printing from the method.
Exercise 3: Case-Insensitive Palindrome
- Write a program that checks
"Madam" without treating uppercase and lowercase letters as different.
- Test the program with another mixed-case word.
Exercise 4: Sentence Palindrome
- Process
"A man, a plan, a canal: Panama".
- Ignore spaces and punctuation.
- Convert letters to a consistent case before comparing.
Exercise 5: Count a Character
- Store the text
"programming".
- Count the occurrences of
'm'.
- Print the result.
Exercise 6: Count All Characters
- Use a HashMap to count every character in a string.
- Print the count of each distinct character.
- Repeat the exercise using LinkedHashMap and compare the output order.
Exercise 7: Find Duplicate Characters
- Write a method that identifies characters occurring more than once.
- Test it with
"success" and "banana".
Exercise 8: Count Character Types
- Count letters, digits, spaces, and special characters.
- Test the program with a sentence containing numbers and punctuation.
30. Mini Project: String Analysis Utility
Project objective: Build a console application that analyzes a string and displays its reversed form, palindrome status, and character frequencies.
Project Requirements
- Accept a string value.
- Handle null input safely within the processing method.
- Display the original text and reversed text.
- Check whether the input is a palindrome, ignoring case but preserving spaces and punctuation.
- Count the frequency of each character.
- Display results in the order characters first appear.
Sample Solution
import java.util.LinkedHashMap;
import java.util.Map;
public class StringAnalysisUtility {
static String reverse(String text) {
return new StringBuilder(text).reverse().toString();
}
static boolean isPalindromeIgnoringCase(String text) {
String normalized = text.toLowerCase();
return normalized.equals(reverse(normalized));
}
static Map<Character, Integer> getFrequency(String text) {
Map<Character, Integer> frequency =
new LinkedHashMap<>();
for (char ch : text.toCharArray()) {
frequency.put(
ch,
frequency.getOrDefault(ch, 0) + 1
);
}
return frequency;
}
public static void main(String[] args) {
String text = "level";
if (text == null) {
System.out.println("Input cannot be null.");
return;
}
System.out.println("Original: " + text);
System.out.println("Reversed: " + reverse(text));
System.out.println("Palindrome: "
+ isPalindromeIgnoringCase(text));
System.out.println("Character frequencies:");
for (Map.Entry<Character, Integer> entry
: getFrequency(text).entrySet()) {
System.out.println(
entry.getKey() + " : " + entry.getValue()
);
}
}
}
Sample Output:
Original: level
Reversed: level
Palindrome: true
Character frequencies:
l : 2
e : 2
v : 1
Project extension: Add a menu that allows users to choose between reversing a string, checking a palindrome, counting a selected character, or displaying all character frequencies.
31. Interview Questions and Answers
Q1. What is string reversal?
Answer: String reversal rearranges a string's characters into the opposite order.
Q2. Does Java String have a reverse() method?
Answer: The String class does not have a reverse() method. A common solution is new StringBuilder(text).reverse().toString().
Q3. What is a palindrome?
Answer: A palindrome is a sequence that reads the same forward and backward under the comparison rules defined for the problem.
Q4. How can you check a palindrome without reversing the string?
Answer: Use two pointers, one at the beginning and one at the end, and compare characters while moving toward the center.
Q5. Why is StringBuilder useful for reversing strings?
Answer: It provides a convenient reverse() method and a mutable character sequence, avoiding repeated string concatenation.
Q6. How do you ignore case when checking a palindrome?
Answer: Normalize the case before comparison or use an appropriate case-insensitive comparison strategy.
Q7. How do you ignore spaces and punctuation in a palindrome check?
Answer: Normalize the input by retaining only the desired characters, such as letters and digits, and then compare the normalized sequence with its reverse.
Q8. What is character frequency?
Answer: Character frequency is the number of times a particular character appears in a string.
Q9. How can you count every character in a string?
Answer: Use an array when the character set is bounded, or a map to associate each distinct character with its count.
Q10. What is the difference between HashMap and LinkedHashMap?
Answer: HashMap does not guarantee iteration order, while LinkedHashMap maintains insertion order by default.
Q11. How do you find duplicate characters?
Answer: Count each character's occurrences and display those whose frequency is greater than one.
Q12. What is the time complexity of string reversal?
Answer: Common efficient reversal approaches take O(n) time, where n is the input length.
Q13. What is the time complexity of counting all character frequencies?
Answer: It is typically O(n) expected time with a HashMap, where n is the input length. Printing or sorting the results may add extra work.
Q14. Why should a program check for null input?
Answer: Calling String methods on a null reference causes a NullPointerException. Validation allows the program to handle missing input safely.
Q15. What is the difference between a UTF-16 code unit and a Unicode code point?
Answer: A code unit is a 16-bit unit used in Java strings. A Unicode code point identifies a Unicode character value; some code points require two UTF-16 code units.
32. Quick Revision Checklist
- Understand string reversal and the role of indexes.
- Practice reversing strings with loops, arrays, and StringBuilder.
- Understand recursion and its limitations.
- Know how to check a palindrome with reversal and two pointers.
- Define how case, spaces, and punctuation should be handled.
- Count one character using a counter.
- Count all characters using an array or map.
- Use LinkedHashMap when insertion order matters.
- Find duplicate and most frequent characters.
- Count vowels, consonants, letters, digits, and special characters.
- Understand anagram checking through character sorting or frequency counts.
- Validate empty strings and null references.
- Know the time and space complexity of common solutions.
- Understand the limitations of char-based processing for Unicode text.
33. Conclusion
String reversal, palindrome checking, and character frequency counting are fundamental Core Java programming exercises. They help developers strengthen their understanding of loops, conditional logic, arrays, StringBuilder, maps, character classification, and algorithmic complexity.
Use StringBuilder for straightforward reversal, two pointers for efficient palindrome checks, and frequency arrays or maps to count characters. Always define the expected behavior for case sensitivity, spaces, punctuation, empty input, and Unicode characters before implementing the solution.
Practice the examples and mini project to build the problem-solving skills required for Core Java assignments, coding tests, and technical interviews.
Explore More: Learn more through the JustAcademy Core Java Training Course, register for a course demo, or visit the JustAcademy website.